package com.sy.process.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sy.model.process.ProcessType;
import com.sy.process.mapper.ProcessTemplateMapper;
import com.sy.process.service.ProcessService;
import com.sy.process.service.ProcessTemplateService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sy.process.service.ProcessTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sy.model.process.ProcessTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 审批模板 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-04-09
 */
@Service
public class ProcessTemplateServiceImp extends ServiceImpl<ProcessTemplateMapper, ProcessTemplate> implements ProcessTemplateService {

    @Autowired
    ProcessTypeService processTypeService;
    @Autowired
    ProcessService processService;

    @Override
    public IPage<ProcessTemplate> selectPageProcessTemplate(Page<ProcessTemplate> pageParam) {
        // 1. 正常分页查询
        Page<ProcessTemplate> processTemplatePage = baseMapper.selectPage(pageParam, null);

        // 2. 获得查询出来的list集合
        List<ProcessTemplate> processTemplateList = processTemplatePage.getRecords();

        // 3. 根据id获得名称
        for (ProcessTemplate p : processTemplateList){
            // 获得id
            Long processTypeId = p.getProcessTypeId();

            // 设置查询条件
            LambdaQueryWrapper<ProcessType> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ProcessType::getId, processTypeId);
            ProcessType one = processTypeService.getOne(wrapper);
            if (one == null) continue;

            // 4. 实现封装
            p.setProcessTypeName(one.getName());
        }
        return processTemplatePage;
    }

    @Transactional
    @Override
    public void publish(Long id) {
        ProcessTemplate processTemplate = this.getById(id);
        processTemplate.setStatus(1);
        baseMapper.updateById(processTemplate);

        if (!StringUtils.isEmpty(processTemplate.getProcessDefinitionPath())){
            processService.deployByZip(processTemplate.getProcessDefinitionPath());
        }
    }
}
